<template>
  <video v-if="isVideo(data.url || data.image)" :src="data.url || data.image"
    class="relative z-2 w-full bg-transparent rounded-[6px] object-cover" controls autoplay
    :poster="transformImage(data.cover_url)" x5-playsinline="h5-page" x-webkit-airplay="allow" webkit-playsinline="true"
    playsinline="true"></video>
  <img v-else :src="transformImage(data.url || data.image)"
    class="relative z-2 w-full bg-transparent rounded-[6px] object-cover" :class="{ 'cursor-pointer': data.event_click }"
    @click="onClick(data)" @load="onLoad" />
</template>

<script lang="ts" setup name="SwiperChild">
import { useUIStore } from "@/store/ui";
import { transformImage } from "@/utils/client";


const changeShow: LooseFunction = inject('changeShow')

const props = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
  axisId: {
    type: String,
    default: ''
  },
  realIndex: {
    type: Number,
    default: -1
  },
  swiper: {
    type: Object,
    default: () => ({}),
  }
});
const UI = useUIStore();

onMounted(() => {
  if (isVideo(props.data.url || props.data.image)) {
    onLoad()
  }
})

const isVideo = (name) => {
  if (!name) return false;
  const suffix = name.substring(name.lastIndexOf(".") + 1);
  return ["avi", "mp4", "wmv", "mov"].includes(suffix.toLowerCase());
};

const onClick = useDebounceFn((node) => {
  const clickFn = () => node?.event_click && UI.go({ ...node.event_click, axis_id: props.axisId });
  if (props.swiper) {
    if (props.swiper.realIndex === props.realIndex) clickFn()
    else {
      props.swiper.slideToLoop(props.realIndex)
      setTimeout(clickFn, 300)
    }
  } else {
    clickFn()
  }
}, 200);

const onLoad = () => {
  changeShow()
}
</script>